package iamutkarshtiwari.github.io.ananas.editimage.view;


import iamutkarshtiwari.github.io.ananas.ResourceTable;
import iamutkarshtiwari.github.io.ananas.editimage.utils.RectUtil;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.utils.Color;
import ohos.agp.utils.Matrix;
import ohos.agp.utils.RectFloat;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.IOException;
import java.math.BigDecimal;

public class StickerItem {
    private static final double MIN_SCALE = 0.15f;
    private static final int HELP_BOX_PAD = 25;
    private static final BigDecimal HELP_BOX_PAD_BIG_DECIMAL = new BigDecimal(25);
    private static final int BORDER_STROKE_WIDTH = 8;

    private static final int BUTTON_WIDTH = 30;
    private static final BigDecimal BUTTON_WIDTH_BIG_DECIMAL = new BigDecimal(30);
    //删除按钮监听的范围
    private static final int BUTTON_WIDTH_DELETE = 45;
    private static final BigDecimal BUTTON_WIDTH_DELETE_BIG_DECIMAL = new BigDecimal(45);
    /**
     * 选择添加的图片
     */
    public PixelMap bitmap;
    RectFloat dstRect;
    private RectFloat helpToolsRect;
    private RectFloat deleteRect;
    private RectFloat deleteRect2;
    private RectFloat rotateRect;

    private RectFloat helpBox;
    public Matrix matrix;
    private float roatetAngle = 0;
    boolean isDrawHelpTool = false;
    //    private Paint paint = new Paint();
    private Paint helpBoxPaint = new Paint();

    private float initWidth;

    private PixelMap deleteBit;
    private PixelMap rotateBit;

    RectFloat detectRotateRect;
    RectFloat detectDeleteRect;
    RectFloat detectDeleteRect2;

    StickerItem(Context context) {

        helpBoxPaint.setColor(Color.WHITE);
        helpBoxPaint.setStyle(Paint.Style.STROKE_STYLE);
        helpBoxPaint.setAntiAlias(true);
        helpBoxPaint.setStrokeWidth(BORDER_STROKE_WIDTH);

        Paint dstPaint = new Paint();
        dstPaint.setColor(Color.RED);
        dstPaint.setAlpha(120);

        Paint greenPaint = new Paint();
        greenPaint.setColor(Color.GREEN);
        greenPaint.setAlpha(120);

        try {
            if (deleteBit == null) {
                deleteBit = ImageSource.create(context.getResourceManager().getResource(ResourceTable.Media_ic_close), new ImageSource.SourceOptions()).createPixelmap(null);//BitmapFactory.decodeResource(context.getResources(),
            }
            if (rotateBit == null) {
                rotateBit = ImageSource.create(context.getResourceManager().getResource(ResourceTable.Media_ic_resize), new ImageSource.SourceOptions()).createPixelmap(null);
            }
        } catch (IOException | NotExistException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化添加的图到显示界面上
     *
     * @param addBit     添加的图
     * @param parentView 父容器
     */
    public void init(PixelMap addBit, Component parentView) {
        this.bitmap = addBit;
        int bitWidth = Math.min(addBit.getImageInfo().size.width, parentView.getWidth() >> 1);
        int bitHeight = bitWidth * addBit.getImageInfo().size.height / addBit.getImageInfo().size.width;
        int left = (parentView.getWidth() >> 1) - (bitWidth >> 1);
        int top = (parentView.getHeight() >> 1) - (bitHeight >> 1);
        this.dstRect = new RectFloat(left, top, left + bitWidth, top + bitHeight);

        this.matrix = new Matrix();
        this.matrix.postTranslate(this.dstRect.left, this.dstRect.top);
        this.matrix.postScale((float) bitWidth / addBit.getImageInfo().size.width,
                (float) bitHeight / addBit.getImageInfo().size.height, this.dstRect.left,
                this.dstRect.top);
        initWidth = this.dstRect.getWidth();
        this.isDrawHelpTool = true;
        this.helpBox = new RectFloat(this.dstRect);
        updateHelpBoxRect();

        helpToolsRect = new RectFloat(0, 0, deleteBit.getImageInfo().size.width,
                deleteBit.getImageInfo().size.height);

        BigDecimal leftDecimal = BigDecimal.valueOf(helpBox.left);
        BigDecimal topDecimal = BigDecimal.valueOf(helpBox.top);
        BigDecimal rightDecimal = BigDecimal.valueOf(helpBox.right);
        BigDecimal bottomDecimal = BigDecimal.valueOf(helpBox.bottom);

        deleteRect = new RectFloat(leftDecimal.subtract(BUTTON_WIDTH_BIG_DECIMAL).floatValue(), topDecimal.subtract(BUTTON_WIDTH_BIG_DECIMAL).floatValue()
                , leftDecimal.add(BUTTON_WIDTH_BIG_DECIMAL).floatValue(), topDecimal.add(BUTTON_WIDTH_BIG_DECIMAL).floatValue());
        rotateRect = new RectFloat(rightDecimal.subtract(BUTTON_WIDTH_BIG_DECIMAL).floatValue(), bottomDecimal.subtract(BUTTON_WIDTH_BIG_DECIMAL).floatValue()
                , rightDecimal.add(BUTTON_WIDTH_BIG_DECIMAL).floatValue(), bottomDecimal.add(BUTTON_WIDTH_BIG_DECIMAL).floatValue());
        deleteRect2 = new RectFloat(leftDecimal.subtract(BUTTON_WIDTH_DELETE_BIG_DECIMAL).floatValue(), topDecimal.subtract(BUTTON_WIDTH_DELETE_BIG_DECIMAL).floatValue()
                , leftDecimal.add(BUTTON_WIDTH_DELETE_BIG_DECIMAL).floatValue(), topDecimal.add(BUTTON_WIDTH_DELETE_BIG_DECIMAL).floatValue());

        detectRotateRect = new RectFloat(rotateRect);
        detectDeleteRect = new RectFloat(deleteRect);
        detectDeleteRect2 = new RectFloat(deleteRect2);
    }

    /**
     * 更新对应的矩阵值
     */
    private void updateHelpBoxRect() {
        this.helpBox.left = BigDecimal.valueOf(this.helpBox.left).subtract(HELP_BOX_PAD_BIG_DECIMAL).floatValue();
        this.helpBox.right = BigDecimal.valueOf(this.helpBox.right).add(HELP_BOX_PAD_BIG_DECIMAL).floatValue();
        this.helpBox.top = BigDecimal.valueOf(this.helpBox.top).subtract(HELP_BOX_PAD_BIG_DECIMAL).floatValue();
        this.helpBox.bottom = BigDecimal.valueOf(this.helpBox.bottom).add(HELP_BOX_PAD_BIG_DECIMAL).floatValue();

    }

    /**
     * 更新矩阵的坐标
     *
     * @param dx x轴偏移
     * @param dy y轴偏移
     */
    void updatePos(final float dx, final float dy) {
        this.matrix.postTranslate(dx, dy);

        dstRect.translate(dx, dy);

        helpBox.translate(dx, dy);
        deleteRect.translate(dx, dy);
        deleteRect2.translate(dx, dy);
        rotateRect.translate(dx, dy);

        this.detectRotateRect.translate(dx, dy);
        this.detectDeleteRect.translate(dx, dy);
        this.detectDeleteRect2.translate(dx, dy);
    }

    /**
     * 更新角度以及图片缩放
     *
     * @param oldx 旧的X轴点
     * @param oldy 旧的Y轴点
     * @param dx   X轴点
     * @param dy   Y轴点
     */
    void updateRotateAndScale(final float oldx, final float oldy, final float dx, final float dy) {
        float c_x = dstRect.getCenter().getPointX();
        float c_y = dstRect.getCenter().getPointY();

        double pointX = this.detectRotateRect.getCenter().getPointX();
        double pointY = this.detectRotateRect.getCenter().getPointY();

        double n_x = pointX + dx;
        double n_y = pointY + dy;

        double xa = pointX - c_x;
        double ya = pointY - c_y;

        double xb = n_x - c_x;
        double yb = n_y - c_y;

        double srcLen = Math.sqrt(xa * xa + ya * ya);
        double curLen = Math.sqrt(xb * xb + yb * yb);

        double scale = curLen / srcLen;

        double newWidth = (double) dstRect.getWidth() * scale;
        if (newWidth / (double) initWidth < MIN_SCALE) {
            return;
        }

        float scaleF = BigDecimal.valueOf(scale).floatValue();
        this.matrix.postScale(scaleF, scaleF, this.dstRect.getCenter().getPointX(),
                this.dstRect.getCenter().getPointY());
        RectUtil.scaleRect(this.dstRect, scaleF);

        helpBox.modify(dstRect);
        updateHelpBoxRect();

        rotateRect.translateTo((float) ((double) helpBox.right - BUTTON_WIDTH), (float) ((double) helpBox.bottom
                - BUTTON_WIDTH));
        deleteRect.translateTo((float) ((double) helpBox.left - BUTTON_WIDTH), (float) ((double) helpBox.top
                - BUTTON_WIDTH));
        deleteRect2.translateTo((float) ((double) helpBox.left - BUTTON_WIDTH_DELETE), (float) ((double) helpBox.top
                - BUTTON_WIDTH_DELETE));


        detectRotateRect.translateTo((float) ((double) helpBox.right - BUTTON_WIDTH), (float) ((double) helpBox.bottom
                - BUTTON_WIDTH));
        detectDeleteRect.translateTo((float) ((double) helpBox.left - BUTTON_WIDTH), (float) ((double) helpBox.top
                - BUTTON_WIDTH));

        detectDeleteRect2.translateTo((float) ((double) helpBox.left - BUTTON_WIDTH_DELETE), (float) ((double) helpBox.top
                - BUTTON_WIDTH_DELETE));

        double cos = (xa * xb + ya * yb) / (srcLen * curLen);
        if (cos > 1 || cos < -1)
            return;
        double angle = Math.toDegrees(Math.acos(cos));

        double calMatrix = xa * yb - xb * ya;

        int flag = calMatrix > 0 ? 1 : -1;
        angle = flag * angle;

        roatetAngle += angle;
        this.matrix.postRotate(BigDecimal.valueOf(angle).floatValue(), this.dstRect.getCenter().getPointX(),
                this.dstRect.getCenter().getPointY());

        RectUtil.rotateRect(this.detectRotateRect, this.dstRect.getCenter().getPointX(),
                this.dstRect.getCenter().getPointY(), roatetAngle);
        RectUtil.rotateRect(this.detectDeleteRect, this.dstRect.getCenter().getPointX(),
                this.dstRect.getCenter().getPointY(), roatetAngle);

        RectUtil.rotateRect(this.detectDeleteRect2, this.dstRect.getCenter().getPointX(),
                this.dstRect.getCenter().getPointY(), roatetAngle);
    }

    /**
     * 绘制新图
     *
     * @param canvas 画布
     */
    void draw(Canvas canvas) {
//        canvas.drawBitmap(this.bitmap, this.matrix, null);
        canvas.save();
        canvas.rotate(roatetAngle, helpBox.getCenter().getPointX(), helpBox.getCenter().getPointY());
        canvas.drawPixelMapHolderRect(new PixelMapHolder(bitmap), helpBox, new Paint());
        canvas.restore();

        if (this.isDrawHelpTool) {
            canvas.save();
            canvas.rotate(roatetAngle, helpBox.getCenter().getPointX(), helpBox.getCenter().getPointY());
            canvas.drawRoundRect(helpBox, 10, 10, helpBoxPaint);


            canvas.drawPixelMapHolderRect(new PixelMapHolder(deleteBit), helpToolsRect, deleteRect, new Paint());
            canvas.drawPixelMapHolderRect(new PixelMapHolder(rotateBit), helpToolsRect, rotateRect, new Paint());
            canvas.restore();
        }
    }
}
